package com.health.viewscontrols.settings;

import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.health.db.DbManager;
import com.health.db.FDbManager;
import com.health.httpbean.HttpConstant;
import com.health.httpbean.HttpNewConstant;
import com.health.tablebean.BTDevice;
import com.health.tablebean.READ_SFZ;
import com.health.tools.FileUtils;
import com.health.view.spinner.NiceSpinner;
import com.health.viewscontrols.NovaActivity;
import com.health.viewscontrols.NovaApplication;
import com.health.R;
import com.health.UpdateVersion;
import com.health.model.SystemSettings;
import com.health.tools.DownLoadTools;
import com.health.tools.GetPostJTYS;
import com.health.tools.GlobalConts;
import com.health.tools.SPUtil;
import com.health.viewscontrols.NovaPtActivity;
import com.health.viewscontrols.SplashActivity;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统设置
 * 
 * @author 田相伟
 *
 */
public class SystemSettingActivity extends NovaPtActivity implements View.OnClickListener {
	private Button set_update;// 更新

	public EditText ftp_path;// ftp地址
	public EditText ftp_account;// ftp帐号
	public EditText ftp_passward;// ftp密码
	public EditText db_path;// 数据库地址
	public EditText date_tongbu_path;// 数据同步地址
	public EditText shangchuan_yanzheng;// 上传验证接口
	public EditText shengji_hao;// 产品升级号
	public EditText zidong_shengji;// 自动升级
	public Button save;// 保存
	public Button cancle;// 取消
	private static String pathStr = Environment.getExternalStorageDirectory() + GlobalConts.TYPE_DBFILENAME;
	private Button fanhui;
	private Button up;
	private TextView title;
	private Button set_xzq;
	public EditText et_uploadaddress;// 公卫上传地址
	public EditText et_shouquanaddress;// 公卫上传地址
	public EditText et_sf_url;// 随访上传地址
	public EditText et_new_url;// 随访上传地址 新平台

	private Button set_dzjmjkk;// 设置居民电健康卡
	Button delete;//删除文件

	private EditText et_upload_jtys_address;//家庭医生上传地址
    private LinearLayout ll_finish;
    private TextView tv_title;
    private NiceSpinner select_dk;
	private ArrayList<String> sfzlist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_systemsetting);
		findViews();

		setListeners();
//		initData();

	}

	public void initData() {

		String sp_url_new = SPStaticUtils.getString(HttpNewConstant.sp_url_new, HttpNewConstant.defaultURl);
		if (!TextUtils.isEmpty(sp_url_new)) {
			et_new_url.setText(sp_url_new + "");
		}


		String sp_url = SPStaticUtils.getString(HttpConstant.sp_url, "");
		if (!TextUtils.isEmpty(sp_url)) {
			et_sf_url.setText(sp_url+"");
		}

		Log.e("xiaoxin", "initData: " + HttpConstant.getHttpUrlUpLoadData());
		Log.e("xiaoxin", "initData: " + HttpConstant.getHttpUrlAndroidRegister());

		if (TextUtils.isEmpty(db_path.getText())) {
			db_path.setText(pathStr + "/EhrApp.db");
		}
		SystemSettings sys = SPUtil.getSysSettings(SystemSettingActivity.this);
		if (sys != null) {

			if (!TextUtils.isEmpty(sys.getFtpAddress())) {
				ftp_path.setText(sys.getFtpAddress());
			}
			if (!TextUtils.isEmpty(sys.getFtpAccount())) {
				ftp_account.setText(sys.getFtpAccount());
			}
			if (!TextUtils.isEmpty(sys.getFtpPassword())) {
				ftp_passward.setText(sys.getFtpPassword());
			}
			if (!TextUtils.isEmpty(sys.getDb_path())) {
				db_path.setText(sys.getDb_path());
			}
			if (!TextUtils.isEmpty(sys.getDate_tongbu_path())) {
				date_tongbu_path.setText(sys.getDate_tongbu_path());
			}
			if (!TextUtils.isEmpty(sys.getShangchuan_yanzheng())) {
				shangchuan_yanzheng.setText(sys.getShangchuan_yanzheng());
			}
			if (!TextUtils.isEmpty(sys.getShengji_hao())) {
				shengji_hao.setText(sys.getShengji_hao());
			}
			if (!TextUtils.isEmpty(sys.getZidong_shengji())) {
				zidong_shengji.setText(sys.getZidong_shengji());
			}
		}
		et_uploadaddress.setText(TextUtils.isEmpty(SPUtil.getSTR_UPLOAD_ADDRESS(SystemSettingActivity.this)) ? ""
				: SPUtil.getSTR_UPLOAD_ADDRESS(SystemSettingActivity.this));
		et_upload_jtys_address.setText(TextUtils.isEmpty(SPUtil.getSTR_UPLOAD_JTYS_ADDRESS(SystemSettingActivity.this)) ? ""
				: SPUtil.getSTR_UPLOAD_JTYS_ADDRESS(SystemSettingActivity.this));
		et_shouquanaddress.setText(TextUtils.isEmpty(SPUtil.getStrShouquanAddress(SystemSettingActivity.this)) ? ""
				: SPUtil.getStrShouquanAddress(SystemSettingActivity.this));
	}

	/**
	 * 显示同步数据
	 * 
	 * @param context
	 * @author 王婷婷
	 * @date 2017年3月14日 下午2:51:30
	 */
	private void showSynDialog(final Context context) {
		// 获得SharedPreferences对象
		// 获得SharedPreferences.Editor对象
		LayoutInflater inflater = LayoutInflater.from(this);
		final View textEntryView = inflater.inflate(R.layout.syn_dialog, null);
		final EditText ed_xzbh = (EditText) textEntryView.findViewById(R.id.ed_xzbh);
		ed_xzbh.setText(SPUtil.getstr_xzq(SystemSettingActivity.this));
		final EditText ed_pwd = (EditText) textEntryView.findViewById(R.id.ed_pwd);
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
		builder.setView(textEntryView);
		builder.setPositiveButton("同步", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String str_xzbh = ed_xzbh.getText().toString();
				if (TextUtils.isEmpty(str_xzbh) || str_xzbh.length() != 6) {
					showTextDialog("请输入正确的行政编号");
					return;
				}
				String str_pwd = ed_pwd.getText().toString();
				if (str_pwd.equals("nova8888")) {
					String fileURl = GlobalConts.getUrlPost() + GetPostJTYS.URL_DBSYNC + "?orgDistrictId=" + str_xzbh;
					Log.w("eeeeeeeeeeeeee", fileURl);
					if (!TextUtils.isEmpty(fileURl)) {
						SPUtil.setstr_xzq(SystemSettingActivity.this, str_xzbh);
						DownLoadTools downLoad = new DownLoadTools(context);
						downLoad.downloadFile(fileURl, NovaApplication.dbPath);
					}
				} else {
					showTextDialog("密码有误，请重新输入");
				}

			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}

	@Override
	public void findViews() {
		et_sf_url = (EditText) findViewById(R.id.et_sf_url);
		et_new_url = (EditText) findViewById(R.id.et_new_url);
		et_shouquanaddress = (EditText) findViewById(R.id.et_shouquanaddress);

		et_sf_url.setVisibility(View.GONE);

		ftp_path = (EditText) findViewById(R.id.ftp_path);
        ll_finish = (LinearLayout)findViewById(R.id.ll_finish);
		select_dk = (NiceSpinner)findViewById(R.id.select_dk);
		ftp_account = (EditText) findViewById(R.id.ftp_acount);
		ftp_passward = (EditText) findViewById(R.id.ftp_passward);
		db_path = (EditText) findViewById(R.id.db_path);
		date_tongbu_path = (EditText) findViewById(R.id.date_tongbu_path);
		shangchuan_yanzheng = (EditText) findViewById(R.id.shangchuan_yanzheng);
		save = (Button) findViewById(R.id.save);
		cancle = (Button) findViewById(R.id.cancle);
		shengji_hao = (EditText) findViewById(R.id.shengji_hao);
		set_update = (Button) findViewById(R.id.set_update);
		set_dzjmjkk = (Button) findViewById(R.id.set_dzjmjkk);
		delete=findViewById(R.id.set_delete);
        tv_title = (TextView)findViewById(R.id.tv_title);

		int vercode = GlobalConts.getVerCode(getApplicationContext());
		if (vercode == -1) {
			shengji_hao.setText("1");
		} else {
			shengji_hao.setText(String.valueOf(vercode));
		}

		zidong_shengji = (EditText) findViewById(R.id.zidong_shengji);
		fanhui = (Button) findViewById(R.id.btn_back);
		up = (Button) findViewById(R.id.btn_up);
		up.setVisibility(View.GONE);
		title = (TextView) findViewById(R.id.title);
		title.setText("系统设置");
		set_xzq = (Button) findViewById(R.id.set_xzq);
		et_uploadaddress = (EditText) findViewById(R.id.et_uploadaddress);
		et_shouquanaddress = (EditText) findViewById(R.id.et_shouquanaddress);
		try {
			Button bt_save = (Button)findViewById(R.id.bt_save);
			bt_save.setVisibility(View.GONE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		et_upload_jtys_address = (EditText) findViewById(R.id.et_upload_jtys_address);
		try {
			tv_title.setText("系统设置");
		} catch (Exception e) {
			e.printStackTrace();
		}


		sfzlist = new ArrayList<String>();
		sfzlist.add("内置读卡");
		sfzlist.add("外置读卡");
		select_dk.attachDataSource(sfzlist);

		String datainfo = NovaApplication.dkType;
		int indexOf = sfzlist.indexOf(datainfo);
		select_dk.setSelectedIndex(indexOf);

		int dktype = select_dk.getSelectedIndex();
		Log.e("TAG","读卡方式："+dktype);

		EditText et_imei = findViewById(R.id.et_imei);
		et_imei.setText(GlobalConts.generateIMEI(Utils.getApp()));
	}

	@Override
	public void setListeners() {
		set_dzjmjkk.setOnClickListener(this);
		set_update.setOnClickListener(this);

        ll_finish.setOnClickListener(this);

		save.setOnClickListener(this);
		cancle.setOnClickListener(this);
		// 设置行政区
		set_xzq.setOnClickListener(this);
		delete.setOnClickListener(this);
		fanhui.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.set_update:
			// 检测更新
			setUpdataVersion();
			break;
            case R.id.ll_finish:
                finish();
                break;
		case R.id.save:
			// 保存设置
			saveSettings();
			break;
		case R.id.set_delete:
			new AlertDialog.Builder(this).setTitle("确认删除").setMessage("确定删除所有数据吗？")
					.setPositiveButton("删除", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							showProgressDialog("正在删除，请稍后");
							deleteDirectory(Environment.getExternalStorageDirectory() + GlobalConts.TYPE_DBFILENAME);
							deleteDirectory(Environment.getExternalStorageDirectory() + "/PublicHealth");
							deleteDirectory(Environment.getExternalStorageDirectory() + "/NovaJTYS");
							deleteDirectory(Environment.getExternalStorageDirectory() + "/ECGDATA");
							cancelProgressDialog();
							SPUtil.setIsShiYong(SystemSettingActivity.this,true);
							showTextDialog("删除成功");
							reStartApp();

						}
					}).setNegativeButton("取消", null).show();

				break;
		case R.id.cancle:
			// 取消
			finish();
			break;
		case R.id.set_xzq:
			// 设置行政区
			showSynDialog(SystemSettingActivity.this);
			break;
		case R.id.set_dzjmjkk:
			// 设置居民电子档案签
			Intent intent = new Intent(SystemSettingActivity.this, SystemSettingJMDZDAActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_back:
			// 返回
			finish();
			break;
		default:
			break;
		}
	}

	private void reStartApp() {
		Intent intent = new Intent(this, SplashActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		this.startActivity(intent);
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	/**
	 * 设置更新
	 * 
	 * @author 王婷婷
	 * @date 2017年12月11日 下午4:34:34
	 */
	private void setUpdataVersion() {
		try {
			if (!GlobalConts.isNetworkAvailable(SystemSettingActivity.this)) {
				showTextDialog("请检查网络");
				return;
			}
			UpdateVersion up = new UpdateVersion(SystemSettingActivity.this);
			up.setSetDialogFlag(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存数据
	 * 
	 * @author 王婷婷
	 * @date 2017年12月11日 下午4:35:26
	 */
	private void saveSettings() {

		if (!TextUtils.isEmpty(et_sf_url.getText().toString().trim())) {
			SPStaticUtils.put(HttpConstant.sp_url,et_sf_url.getText().toString().trim());
		}

		if (!TextUtils.isEmpty(et_new_url.getText().toString().trim())) {
			SPStaticUtils.put(HttpNewConstant.sp_url_new,et_new_url.getText().toString().trim());
		}

		// Editor editor = MyPreferences.edit();
		// editor.putString("ftpAddress",
		// ftp_path.getText().toString());
		// editor.putString("ftpAccount",
		// ftp_account.getText().toString());
		// editor.putString("ftpPassword",
		// ftp_passward.getText().toString());
		// editor.putString("db_path", db_path.getText().toString());
		// editor.putString("date_tongbu_path",
		// date_tongbu_path.getText().toString());
		// editor.putString("shangchuan_yanzheng",
		// shangchuan_yanzheng.getText().toString());
		// editor.putString("shengji_hao",
		// shengji_hao.getText().toString());
		// editor.putString("zidong_shengji",
		// zidong_shengji.getText().toString());
		// editor.commit();
		SystemSettings sys = new SystemSettings();
		sys.setFtpAddress(ftp_path.getText().toString());
		sys.setFtpAccount(ftp_account.getText().toString());
		sys.setFtpPassword(ftp_passward.getText().toString());
		sys.setDb_path(db_path.getText().toString());
		sys.setDate_tongbu_path(date_tongbu_path.getText().toString());
		sys.setShangchuan_yanzheng(shangchuan_yanzheng.getText().toString());
		sys.setShengji_hao(shengji_hao.getText().toString());
		sys.setZidong_shengji(zidong_shengji.getText().toString());
		SPUtil.setSysSettings(SystemSettingActivity.this, sys);
		SPUtil.setSTR_UPLOAD_ADDRESS(SystemSettingActivity.this,
				TextUtils.isEmpty(et_uploadaddress.getText().toString().trim()) ? ""
						: et_uploadaddress.getText().toString().trim());
		SPUtil.setStrShouquanAddress(SystemSettingActivity.this,
				TextUtils.isEmpty(et_shouquanaddress.getText().toString().trim()) ? ""
						: et_shouquanaddress.getText().toString().trim());
		SPUtil.setSTR_UPLOAD_JTYS_ADDRESS(SystemSettingActivity.this,
				TextUtils.isEmpty(et_upload_jtys_address.getText().toString().trim()) ? ""
						: et_upload_jtys_address.getText().toString().trim());
		NovaApplication.updateUrl = TextUtils.isEmpty(et_uploadaddress.getText().toString().trim()) ? ""
				: et_uploadaddress.getText().toString().trim();
		NovaApplication.updateShouquanUrl = TextUtils.isEmpty(et_shouquanaddress.getText().toString().trim()) ? ""
				: et_shouquanaddress.getText().toString().trim();
		NovaApplication.updateJTYSUrl = TextUtils.isEmpty(et_upload_jtys_address.getText().toString().trim()) ? ""
				: et_upload_jtys_address.getText().toString().trim();
		int dktype = select_dk.getSelectedIndex();
		String dk = sfzlist.get(dktype);
		NovaApplication.dkType = TextUtils.isEmpty(dk) ? "" : dk;
		SPStaticUtils.put("sp_dkType", TextUtils.isEmpty(dk) ? "" : dk);
		GlobalConts.showToast(SystemSettingActivity.this, "保存成功");

		finish();
	}


	/**
	 * 删除文件夹以及目录下的文件
	 * @param   filePath 被删除目录的文件路径
	 * @return  目录删除成功返回true，否则返回false
	 */
	public boolean deleteDirectory(String filePath) {
		boolean flag = false;
		//如果filePath不以文件分隔符结尾，自动添加文件分隔符
		if (!filePath.endsWith(File.separator)) {
			filePath = filePath + File.separator;
		}
		File dirFile = new File(filePath);
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		flag = true;
		File[] files = dirFile.listFiles();
		//遍历删除文件夹下的所有文件(包括子目录)
		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile()) {
				//删除子文件
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag) break;
			} else {
				//删除子目录
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) break;
			}
		}
		if (!flag) return false;
		//删除当前空目录
		return dirFile.delete();
	}

	/**
	 *  根据路径删除指定的目录或文件，无论存在与否
	 *@param filePath  要删除的目录或文件
	 *@return 删除成功返回 true，否则返回 false。
	 */
	public boolean DeleteFolder(String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			return false;
		} else {
			if (file.isFile()) {
				// 为文件时调用删除文件方法
				return deleteFile(filePath);
			} else {
				// 为目录时调用删除目录方法
				return deleteDirectory(filePath);
			}
		}
	}

	public boolean deleteFile(String path){
		File file1 = new File(path);
		if (file1.isFile()&&file1.exists()) {
			return file1.delete();
		}else{
			return false;
		}
	}
}
